package p_103

import java.io.BufferedInputStream
import java.io.FileOutputStream
import java.io.IOException
import java.net.URL

class BinarySaver {
    val resourcePath = "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=2737875068,3682183777&fm=26&gp=0.jpg"

    fun doSome() {
        val url = URL(resourcePath)
        try {
            saveBinaryFile(url)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun saveBinaryFile(url: URL) {
        val connection = url.openConnection()
        val contentType = connection.contentType
        val contentLength = connection.contentLength
        if (contentType.startsWith("text/") || contentLength == -1) throw IOException("不是一个二进制文件")

        try {
            val inputStream = connection.getInputStream()
            val bufferdInputStream = BufferedInputStream(inputStream)
            val bytes = ByteArray(contentLength)
            var offset = 0
            while (offset < contentLength) {
                val byteRead = bufferdInputStream.read(bytes, offset, bytes.size - offset)
                if (byteRead == -1) {
                    println("byteRead == -1")
                    break
                }
                offset += byteRead
            }
            if (offset != contentLength) {
                throw IOException("未下载完整文件")
            }
            var fileName = url.file
            fileName = "F:/test/${fileName.substring(fileName.lastIndexOf("/") + 1)}"
            print("-->$fileName")
            val outStream = FileOutputStream(fileName)
            outStream.write(bytes)
            outStream.flush()

            inputStream.close()
            outStream.close()
            println("正常结束-->")
        } catch (e: Exception) {
            e.printStackTrace()
            println("异常-->${e.message}")
        }
    }

}